package com.ww.util.json;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Jackson01 {

    public static void main(String[] args) throws JsonProcessingException {
        test01();
        test02();
        test03();
        test04();
    }

    /**
     * 序列化操作
     */
    public static void test01() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Car car = new Car("yellow", "renault");
        System.out.println(objectMapper.writeValueAsString(car));
    }

    /**
     * 反序列化操作
     */
    public static void test02() throws JsonProcessingException {
        String json = "{\"color\":\"yellow\",\"type\":\"renault\"}";
        ObjectMapper objectMapper = new ObjectMapper();
        Car car = objectMapper.readValue(json, Car.class);
        System.out.println(car);
    }

    /**
     * 反序列化List
     * @throws JsonProcessingException
     */
    public static void test03() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println("反序列化List方法1：");
        long start1 = System.currentTimeMillis();
        String jsonCarArray = "[{\"color\": \"Black\", \"type\": \"BMW\"}, {\"color\":\"Red\", \"type\":\"FIAT\"}]";
        List<Car> listCar = objectMapper.readValue(jsonCarArray, new TypeReference<List<Car>>(){});
        long end1 = System.currentTimeMillis();
        // 5毫秒
        System.out.println("耗时：" + (end1 - start1) + "毫秒");
        listCar.forEach(System.out::println);

        /**
         * 推荐使用（性能更好）
         */
        System.out.println("反序列化List方法2：");
        long start2 = System.currentTimeMillis();
        objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
        Car[] cars = objectMapper.readValue(jsonCarArray, Car[].class);
        long end2 = System.currentTimeMillis();
        // 1毫秒
        System.out.println("耗时：" + (end2 - start2) + "毫秒");
        Arrays.stream(cars).forEach(System.out::println);
    }

    /**
     * 反序列化成Map类型
     * @throws JsonProcessingException
     */
    public static void test04() throws JsonProcessingException {
        String json = "{\"color\": \"Black\", \"type\":{\"a\":22}, \"arr\":[\"aa\", \"bb\"]}";
        Map<String, Object> map = new ObjectMapper().readValue(json, new TypeReference<Map<String, Object>>(){});
        System.out.println("map = " + map);

        String color = (String) map.get("color");
        System.out.println("color = " + color);
    }
}
